package com.hkbigdata.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2024-03-27-17:19
 * @see 2194550857@qq.com
 */
public class Flink001_WordCount_Batch {
    public static void main(String[] args) throws Exception {
        //1.获取环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.读取文件
        DataSource<String> stringDataSource = env.readTextFile("input/word.txt");
        env.setParallelism(1);

        //3.数据拍平
        FlatMapOperator<String, String> stringStringFlatMapOperator = stringDataSource.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] arr = value.split(" ");
                for (int i = 0; i < arr.length; i++) {
                    out.collect(arr[i]);
                }
            }
        });

        //4.将单词映射成元组(spark,1) (flink,1) (flink,1) (flink,1)
        MapOperator<String, Tuple2<String, Integer>> map = stringStringFlatMapOperator.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                return new Tuple2<>(value, 1);
            }
        });

        //5.分组
        UnsortedGrouping<Tuple2<String, Integer>> tuple2UnsortedGrouping = map.groupBy(0);

        //6.聚合
        tuple2UnsortedGrouping.sum(1).print();

    }
}
